package com.zy.servlet.user;

import com.zy.service.AddUserService;
import com.zy.service.impl.AddUserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addUser")
public class AddUserServlet extends HttpServlet {
    private AddUserService addUserService = new AddUserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("AddUserServlet");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("Username: " + username);
        String role = req.getParameter("role");
        String balanceParam = req.getParameter("balance");

        if (username == null || password == null || role == null || balanceParam == null) {
            req.setAttribute("message", "所有字段都是必填的。");
            req.getRequestDispatcher("/admin.jsp").forward(req, resp);
            return;
        }

        try {
            double balance = Double.parseDouble(balanceParam.trim());
            System.out.println(username + " " + password + " " + role + " " + balance);
            boolean result = addUserService.addUser(username, password, role, balance);

            if (result) {
                req.setAttribute("message", "添加成功");
            } else {
                req.setAttribute("message", "添加失败");
            }
        } catch (NumberFormatException e) {
            req.setAttribute("message", "余额必须是一个有效的数字。");
        }

        req.getRequestDispatcher("/admin.jsp").forward(req, resp);

    }

}